#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    //UI初始化
    {
        ui->setupUi(this);
        ui->tbMediaInfo->setMinimumWidth(200);
        ui->tbMediaInfo->setMaximumWidth(200);
        m_videoFrame = QImage(640,480,QImage::Format_ARGB32);
        m_videoFrame.fill(Qt::black);
        
        ui->leVideoUrl->setPlaceholderText("请填写视频地址");
 //       ui->leVideoUrl->setText("D:\\StudyAtHome\\ffmpegstudy\\附件\\test.mp4");
        ui->leVideoUrl->setText("E:\\Haer_SomeTrys\\ffmpegstudy\\附件\\视频素材\\190314223540373995.mp4");

        //开启ffmpeg读线程
        m_ffmpegThread = new TFFmpegThread;
    }
    {
       //打开
       connect(ui->btnOpen,&QPushButton::clicked,this,&MainWindow::slotBtnOpenClicked);
       //关闭
       connect(ui->btnClose,&QPushButton::clicked,this,&MainWindow::slotBtnCloseClicked);
       //媒体信息
       connect(ui->btnClearLog,&QPushButton::clicked,this,&MainWindow::slotBtnClearLogClicked);
       //媒体文件播放完毕
       connect(m_ffmpegThread,&TFFmpegThread::sigMediaFinish,this,&MainWindow::slotMediaFinish,Qt::QueuedConnection);
       //视频帧解码完成
       connect(m_ffmpegThread,&TFFmpegThread::sigGetVideoFrame,this,&MainWindow::slotGetVideoFrame,Qt::QueuedConnection);
    }
    {
        ui->wgtCanvas->installEventFilter(this);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slotGetVideoFrame(const QImage &nvideoframe)
{
    m_videoFrame = nvideoframe;
    ui->wgtCanvas->update();
}

void MainWindow::slotMediaFinish()
{
    m_ffmpegThread->closeMedia();
}

void MainWindow::slotLog(const QString &nlogstr)
{
    ui->tbMediaInfo->append(nlogstr);
}

bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
    if(object == ui->wgtCanvas) {
        if(event->type() == QEvent::Paint) {
            QPainter npainter(ui->wgtCanvas);
            if(!m_videoFrame.isNull()) {
                npainter.drawImage(0,0,m_videoFrame);
            }
        }
    }
    return QWidget::eventFilter(object,event);
}

/*
 * 打开按钮点击
 */
void MainWindow::slotBtnOpenClicked()
{
    m_ffmpegThread->playMedia(ui->leVideoUrl->text());
}

/*
 * 关闭按钮点击
 */
void MainWindow::slotBtnCloseClicked()
{
    m_ffmpegThread->closeMedia();
}

/*
 * 清空日志点击
 */
void MainWindow::slotBtnClearLogClicked()
{
    ui->tbMediaInfo->clear();
}

